<template>
  <view class="w-690rpx wave" id="canvas" :style="getStyle">
    <canvas canvas-id="myCanvas" class="w-full h-full"> </canvas>
  </view>
</template>

<script>
export default {
  name: 'k-wava',
  props: {
    height: {
      type: [String, Number],
      default: 80
    },
    count: {
      type: [String, Number],
      default: 3
    },
    gap: {
      type: [String, Number],
      default: 10
    },
    color: {
      type: String,
      default: '#fff'
    }
  },
  computed: {
    getStyle() {
      return {
        height: `${this.height}rpx`
      }
    }
  },
  data() {
    return {
      timer: null
    }
  },
  created() {
    this.$nextTick(this.initCanvas)
  },
  methods: {
    getRect() {
      return new Promise((resolve, reject) => {
        uni
          .createSelectorQuery()
          .in(this)
          .select('#canvas')
          .boundingClientRect((data) => {
            // data  可以打印data输出看详细数据，有很多数据信息
            resolve(data)
          })
          .exec()
      })
    },
    async initCanvas() {
      const rectInfo = await this.getRect()
      const ctx = uni.createCanvasContext('myCanvas', this)
      console.log(ctx)
      const { height } = rectInfo
      const { width } = rectInfo
      const lines = [
        'rgba(255, 255, 255, .4)',
        'rgba(255, 255, 255, .5)',
        'rgba(255, 255, 255, 0.7)'
      ]

      const boHeight = height / 5
      const posHeight = height / 1.5 // 波浪高度
      const canvasAny = { width, height }
      const requestAnimFrame = (() => {
        // 波浪自执行函数
        return function (callback) {
          setTimeout(callback, 100 / 6)
        }
      })()
      let step = 0
      // 动起来
      const loop = function () {
        ctx.clearRect(0, 0, canvasAny.width, canvasAny.height)
        step++
        // 画三个不同颜色的矩阵
        for (let j = lines.length - 1; j >= 0; j--) {
          // 每个矩阵的角度都不同，每个之间相差100度
          const angle = ((step + j * 100) * Math.PI) / 180
          const deltaHeight = Math.sin(angle) * boHeight
          const deltaHeightRight = Math.cos(angle) * boHeight
          ctx.fillStyle = lines[j]
          ctx.beginPath() // 开始绘制
          ctx.moveTo(0, posHeight + deltaHeight)
          ctx.bezierCurveTo(
            canvasAny.width / 2,
            posHeight + deltaHeight - boHeight,
            canvasAny.width / 2,
            posHeight + deltaHeightRight - boHeight,
            canvasAny.width,
            posHeight + deltaHeightRight
          )
          ctx.lineTo(canvasAny.width, canvasAny.height)
          ctx.lineTo(0, canvasAny.height)
          ctx.lineTo(0, posHeight + deltaHeight)
          ctx.fill() // 上色
          ctx.closePath() // 结束绘制
        }
        ctx.draw()
        requestAnimFrame(loop) // 启动函数
      }

      loop()
    }
  }
}
</script>

<style scoped>
.wave {
  position: absolute;
  left: 30rpx;
  bottom: -4rpx;
}
</style>
